/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.BrandShopDTO;
import com.yami.shop.bean.dto.BrandSigningDTO;
import com.yami.shop.bean.enums.BrandType;
import com.yami.shop.bean.enums.SigningStatus;
import com.yami.shop.bean.model.Brand;
import com.yami.shop.bean.model.BrandLang;
import com.yami.shop.bean.model.BrandShop;
import com.yami.shop.bean.vo.BrandShopVO;
import com.yami.shop.bean.vo.BrandSigningVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.StatusEnum;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.BrandShopMapper;
import com.yami.shop.service.BrandLangService;
import com.yami.shop.service.BrandService;
import com.yami.shop.service.BrandShopService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author lth
 * @Date 2021/7/28 11:26
 */
@Service
@AllArgsConstructor
public class BrandShopServiceImpl extends ServiceImpl<BrandShopMapper, BrandShop> implements BrandShopService {

    private final BrandService brandService;
    private final BrandShopMapper brandShopMapper;
    private final BrandLangService brandLangService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signingBrands(BrandSigningDTO brandSigningDTO, Long shopId, Boolean isPlatform) {
        if (Objects.equals(shopId, Constant.PLATFORM_SHOP_ID)) {
            return;
        }
        List<BrandShopDTO> platformBrandList = brandSigningDTO.getPlatformBrandList();
        List<BrandShopDTO> customizeBrandList = brandSigningDTO.getCustomizeBrandList();
        if (platformBrandList.size() + customizeBrandList.size() > Constant.SIGNING_BRAND_LIMIT_NUM) {
            throw new YamiShopBindException("签约的品牌数量不能超过" + Constant.SIGNING_BRAND_LIMIT_NUM);
        }
        // 删除已签约的信息
        brandShopMapper.delete(Wrappers.lambdaQuery(BrandShop.class).eq(BrandShop::getShopId, shopId));
        // 处理签约的平台品牌
        if (CollUtil.isNotEmpty(platformBrandList)) {
            List<Long> brandIds = platformBrandList.stream().map(BrandShopDTO::getBrandId).collect(Collectors.toList());
            List<Brand> brandList = brandService.list(Wrappers.lambdaQuery(Brand.class).in(Brand::getBrandId, brandIds));
            if (brandList.size() != platformBrandList.size()) {
                throw new YamiShopBindException("平台品牌签约信息错误，请刷新后重试");
            }
            // 插入平台品牌签约关联信息
            brandShopMapper.insertBatch(shopId, platformBrandList, BrandType.PLATFORM.value(), isPlatform ? SigningStatus.SUCCESS.value() : SigningStatus.PENDING_REVIEW.value());
        }
        // 处理新增的自定义品牌
        // 查询之前新增的自定义品牌列表
        List<Brand> oldBrandList = brandService.list(Wrappers.lambdaQuery(Brand.class).eq(Brand::getShopId, shopId));
        if (CollUtil.isNotEmpty(oldBrandList)) {
            // 删除店铺自定义品牌
            brandService.getBaseMapper().delete(Wrappers.lambdaQuery(Brand.class).eq(Brand::getShopId, shopId));
            brandLangService.getBaseMapper().delete(Wrappers.lambdaQuery(BrandLang.class).in(BrandLang::getBrandId, oldBrandList.stream().map(Brand::getBrandId).collect(Collectors.toList())));
        }
        if (CollUtil.isNotEmpty(customizeBrandList)) {
            // 重新新增店铺自定义
            customizeBrandList.forEach(item -> {
                item.setShopId(shopId);
                item.setBrandId(null);
                item.setIsTop(0);
                item.setSeq(0);
                item.setStatus(0);
            });
            brandService.insertBatchByBrandShopList(customizeBrandList);
            brandShopMapper.insertBatch(shopId, customizeBrandList, BrandType.CUSTOMIZE.value(), isPlatform ? SigningStatus.SUCCESS.value() : SigningStatus.PENDING_REVIEW.value());
            brandLangService.insertBatch(customizeBrandList, LanguageEnum.LANGUAGE_EN.getLang());
            brandLangService.insertBatch(customizeBrandList, LanguageEnum.LANGUAGE_ZH_CN.getLang());
        }
    }

    @Override
    public BrandSigningVO listSigningByShopId(Long shopId, Integer status) {
        // 查询平台品牌签约列表
        List<BrandShopVO> platformBrandList = brandShopMapper.listByShopIdAndType(shopId, BrandType.PLATFORM.value(), I18nMessage.getLang(), status);
        // 查询店铺自定义品牌签约列表
        List<BrandShopVO> customizeBrandList = brandShopMapper.listByShopIdAndType(shopId, BrandType.CUSTOMIZE.value(), I18nMessage.getLang(), status);
        BrandSigningVO brandSigningVO = new BrandSigningVO();
        brandSigningVO.setCustomizeBrandList(customizeBrandList);
        brandSigningVO.setPlatformBrandList(platformBrandList);
        return brandSigningVO;
    }

    @Override
    public void insertBatchByShopId(List<BrandShopDTO> brandShopList, Long shopId, Integer status) {
        if (CollUtil.isEmpty(brandShopList)) {
            return;
        }
        int signedCount = brandShopMapper.selectCount(Wrappers.lambdaQuery(BrandShop.class).eq(BrandShop::getShopId, shopId));
        if (signedCount + brandShopList.size() > Constant.SIGNING_BRAND_LIMIT_NUM) {
            throw new YamiShopBindException("签约的品牌数量不能超过" + Constant.SIGNING_BRAND_LIMIT_NUM);
        }
        brandShopMapper.insertBatch(shopId, brandShopList, BrandType.PLATFORM.value(), status);
    }

    @Override
    public void updateCustomBrandToPlatformBrandByShopId(Long shopId) {
        brandService.updateShopIdAndStatusByShopId(shopId, StatusEnum.ENABLE.value(), Constant.PLATFORM_SHOP_ID);
        brandShopMapper.updateTypeByShopId(shopId, BrandType.PLATFORM.value());
    }

    @Override
    public void changeStatusByShopIdAndStatus(Long shopId, Integer oldStatus, Integer newStatus) {
        brandShopMapper.changeStatusByShopIdAndStatus(shopId, oldStatus, newStatus);
    }

    @Override
    public void deleteByBrandId(Long brandId) {
        brandShopMapper.delete(Wrappers.lambdaQuery(BrandShop.class).eq(BrandShop::getBrandId, brandId));
    }

    @Override
    public IPage<BrandShopVO> pageSigningByShopId(PageParam<BrandShopVO> page, BrandShopDTO brandShop) {
        IPage<BrandShopVO> res = brandShopMapper.pageSigningByShopId(page, brandShop, I18nMessage.getLang());
        return res;
    }

    @Override
    public void deleteByShopIdAndBrandId(Long shopId, Long brandId) {
        int count = brandShopMapper.delete(Wrappers.lambdaQuery(BrandShop.class).eq(BrandShop::getShopId, shopId).eq(BrandShop::getBrandId, brandId));
        if (count != 1) {
            throw new YamiShopBindException("删除失败");
        }
    }

    @Override
    public void insertBatchByBrandShopListAndShopId(List<BrandShop> brandShopList, Long shopId, Integer status) {
        if (CollUtil.isEmpty(brandShopList)) {
            return;
        }
        int signedCount = brandShopMapper.selectCount(Wrappers.lambdaQuery(BrandShop.class).eq(BrandShop::getShopId, shopId));
        if (signedCount + brandShopList.size() > Constant.SIGNING_BRAND_LIMIT_NUM) {
            throw new YamiShopBindException("签约的品牌数量不能超过" + Constant.SIGNING_BRAND_LIMIT_NUM);
        }
        brandShopMapper.insertBatchByBrandShopList(shopId, brandShopList, BrandType.PLATFORM.value(), status);
    }
}
